package com.gzx.plugin.tjzy.modular.sms.receipt.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fhs.trans.service.impl.TransService;
import com.google.common.collect.Lists;
import com.gzx.plugin.tjzy.modular.sms.receipt.bo.GzxSmsReceiptQueryBo;
import com.gzx.plugin.tjzy.modular.sms.receipt.entity.GzxSmsReceipt;
import com.gzx.plugin.tjzy.modular.sms.receipt.mapper.GzxSmsReceiptMapper;
import com.gzx.plugin.tjzy.modular.sms.receipt.service.GzxSmsReceiptService;
import com.gzx.plugin.tjzy.modular.sms.receipt.vo.GzxSmsReceiptVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.consts.IntConstant;
import vip.xiaonuo.common.util.CommonCryptogramUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.apache.commons.lang.StringEscapeUtils.escapeSql;

/**
 * @author zjt
 * @description
 * @date 2025/3/11 15:15
 */
@Service
@DS("sms")
@RequiredArgsConstructor
public class GzxSmsReceiptServiceImpl implements GzxSmsReceiptService {

    private final GzxSmsReceiptMapper smsReceiptMapper;

    private final TransService transService;

    @Override
    public Page<GzxSmsReceiptVo> pageList(GzxSmsReceiptQueryBo smsRecordQueryBo) {
        return smsReceiptMapper.selectVoPage(new Page<>(smsRecordQueryBo.getCurrent(), smsRecordQueryBo.getSize()), Wrappers.<GzxSmsReceipt>lambdaQuery()
                .eq(StringUtils.isNotEmpty(smsRecordQueryBo.getSupplierCode()), GzxSmsReceipt::getSupplierCode, smsRecordQueryBo.getSupplierCode())
                .eq(StringUtils.isNotEmpty(smsRecordQueryBo.getPhone()), GzxSmsReceipt::getPhone, smsRecordQueryBo.getPhone())
                //短信回执新增日期范围查询
                .between(StringUtils.isNotBlank(smsRecordQueryBo.getBeginTime()) && StringUtils.isNotBlank(smsRecordQueryBo.getEndTime()), GzxSmsReceipt::getCreateTime, smsRecordQueryBo.getBeginTime(), smsRecordQueryBo.getEndTime())
                .orderByDesc(GzxSmsReceipt::getId));
    }

    /**
     * 保存短信发送状态
     *
     * @param smsReceiptList
     */
    @Override
    public void saveSMSReceipt(List<GzxSmsReceipt> smsReceiptList) {
        List<List<GzxSmsReceipt>> batchList = Lists.partition(smsReceiptList, IntConstant.VALUE_1000);
        for (List<GzxSmsReceipt> batch : batchList) {
            String batchSql = batch.stream()
                    .map(s -> String.format("('%s', '%s','%s', %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
                            escapeSql(s.getBatchNumber()),
                            escapeSql(s.getProjectCode()),
                            escapeSql(s.getSupplierCode()),
                            escapeSql(String.valueOf(s.getFlagType())),
                            escapeSql(CommonCryptogramUtil.doSm1AesEncrypt(s.getPhone())),
                            escapeSql(s.getSendTime()),
                            escapeSql(s.getMsgId()),
                            escapeSql(String.valueOf(s.getMappingStatus())),
                            escapeSql(s.getResultCode()),
                            escapeSql(s.getResultName()),
                            escapeSql(s.getAllDetail()),
                            escapeSql(String.valueOf(s.getTenantId()))
                    ))
                    .collect(Collectors.joining(", ")).replace("'null'", "null");
            smsReceiptMapper.insertBatchSql(batchSql);
        }
    }

    /**
     * 查询短信发送详情
     *
     * @param batchNumber
     * @param phone
     * @return
     */
    @Override
    public String getSendDetail(String batchNumber, String phone) {
        List<GzxSmsReceiptVo> smsRecordList = smsReceiptMapper.selectVoList(Wrappers.<GzxSmsReceipt>lambdaQuery()
                .select(GzxSmsReceipt::getSupplierCode, GzxSmsReceipt::getSendTime, GzxSmsReceipt::getResultCode)
                .eq(GzxSmsReceipt::getBatchNumber, batchNumber)
                .eq(GzxSmsReceipt::getPhone, CommonCryptogramUtil.doSm1AesEncrypt(phone))
                .orderByAsc(GzxSmsReceipt::getId));
        if (CollectionUtil.isNotEmpty(smsRecordList)) {
            transService.transBatch(smsRecordList);
            Map<String, GzxSmsReceiptVo> smsRecordMap = smsRecordList.stream().collect(Collectors.toMap(GzxSmsReceiptVo::getSupplierCode, Function.identity(), (oldVal, newVal) -> oldVal));
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, GzxSmsReceiptVo> entry : smsRecordMap.entrySet()) {
                sb.append(entry.getValue().getSupplierName()).append("|");
                sb.append(entry.getValue().getSendTime()).append("|");
                sb.append(entry.getValue().getResultCode()).append("\n");
            }
            // 移除最后一个追加的换行符
            if (!sb.isEmpty() && sb.charAt(sb.length() - 1) == '\n') {
                sb.setLength(sb.length() - 1);
            }
            return sb.toString();
        }
        return "";
    }

    /**
     * 根据批次号统计短信发送结果
     *
     * @param batchNumber
     * @return
     */
    @Override
    public Map<String, Object> countByBatchNumber(String batchNumber) {
        List<Map<String, Object>> mapList = smsReceiptMapper.countByBatchNumber(batchNumber);
        Map<String, Object> resultMap = new HashMap<>();
        for (Map<String, Object> map : mapList) {
            resultMap.put(String.valueOf(map.get("resultCode")), map.get("count"));
        }
        return resultMap;
    }
}
